#include <signal.h>

#include "connection.hpp"
#include "acceptor_manager.hpp"

#include "protocol_all.hpp"
#include "protocol_parser.hpp"

#include "processor.hpp"

#include "base.hpp"

using namespace mina;
using namespace protocol;

#ifdef _DEBUG 
 
#define MAX_LOOP        500000LLU 
 
#define MAX_THREAD_NUM  4
#define MAX_CONNECTOR_NUM_FOR_TEST 1
 
#endif 

const char * log_config = "./logger.properties";

log4cplus::Logger g_logger = log4cplus::Logger::getInstance("global_logger");

AcceptorManager * g_acceptor_manager = NULL;

ProtocolParser *  g_protocol_parser  = NULL;
Processor      *  g_processor        = NULL;

bool init(long epoll_timeout)
{
	log4cplus::PropertyConfigurator::doConfigure(log_config);

	signal(SIGPIPE, SIG_IGN);

# ifdef _MULTIPLE_THREAD
	g_acceptor_manager = AcceptorCreator::create(MAX_THREAD_NUM, 
				1024 * 4, 1024 * 120, 32, 1024, epoll_timeout);
# else
	g_acceptor_manager = AcceptorCreator::create(1024 * 4, 1024 * 1024 * 30, 1024, epoll_timeout);
# endif

	g_protocol_parser = new ProtocolParser;
	g_processor       = new Processor;

	g_acceptor_manager->add_acceptor(NULL, 8000, *g_protocol_parser, *g_processor);

	return true;
}

int main(int argc, char * argv[])
{
	if (argc != 2)
	{
		std::cout << "Usage: " << argv[0] << " epoll_timeout" << std::endl;
		return 0;
	}

	long epoll_timeout   = ::strtol(argv[1], NULL, 10);

	init(epoll_timeout);

	int64_t start  = Utility::get_now_ms_time();

	while (true)
	{
		g_acceptor_manager->poll();
		g_acceptor_manager->process_message();
	}

	int64_t end = Utility::get_now_ms_time();

	std::cout << "total use time: " << (end - start) << " ms"
					<< ", start: " << start << ", end: " << end << std::endl;

	AcceptorCreator::destroy(*g_acceptor_manager);

	return 0;
}

